(function ($) {
    $.fn.myPagination = function (param) {
        return init(param, $(this))
    };

    function init(param, obj) {
       var selectNum= $(obj).data('pageNum');
       if (!!!selectNum){
           selectNum=10;
       }
        var defaults = {
            currPage: 1,
            perPage: selectNum,
            pageCount: selectNum,
            allCount: 0,
            pageNumber: selectNum,
            saveChecked:false,
            checkedId:[],
            rowNumber:false,
            rowCheck:true,
            singleCheck:false,
            multiCheck:true,
            contextMenu:false,
            contextMenuParam:{},
            showTitle:false,
            cssStyle: 'badoo',
            ajax: {
                on: false,
                type: "POST",
                pageCountId: 'pageCount',
                allCountId: 'allCount',
                url: "jsonTest.php",
                dataType: 'json',
                param: false,
                onClick: function () {
                    return false
                },
                ajaxStart: function () {
                    return false
                },
                callback: function (data) {
                    return false
                }
            },
            panel: {
                first: '首页',
                last: '尾页',
                next: '下一页',
                prev: '上一页',
                first_on: true,
                last_on: true,
                next_on: true,
                prev_on: true,
                links: '#',
                tipInfo_on: false,
                tipInfo: '<span>&nbsp;&nbsp;跳{currText}/{sumPage}页</span>',
                tipInfo_css: {
                    width: '22px'
                }
            }
        };

        function getParam() {
            var param = "page=" + opts.currPage + "&perpage=" + opts.perPage;
            if (opts.ajax.param) { /* param += "&" + opts.ajax.param */
                param += "&" + $("#searchbox form").serialize();
            }
            ;
            return param
        }
        ;

        function checkInputPage(val) {
            var msg;
            if (val < 1) {
                msg = "输入值不能小于1"
            }
            ;
            var patrn = /^[0-9]{1,8}$/;
            if (!patrn.exec(val)) {
                msg = "请输入正确的数字"
            }
            ;
            if (val > opts.pageCount) {
                msg = "输入值不能大于总页数"
            }
            ;
            if (msg) {
                alert(msg);
                return false
            }
            ;
            return true
        }
        ;

        function getPanelTipInfo() {
            var str = "";
            if (opts.panel.tipInfo_on) {
                var input = "<input type='text' value='" + opts.currPage
                    + "' >";
                var info = opts.panel.tipInfo;
                info = info.replace("{currText}", input);
                info = info.replace("{sumPage}", opts.pageCount);
                info = $(info);
                input = info.children(":text:first");
                var css = opts.panel.tipInfo_css;
                for (var temp in css) {
                    var val = eval("css." + temp);
                    input.css(temp, val)
                }
                ;
                str = info.html()
            }
            ;
            return str
        }
        ;

        function getpageCount(perPage) {
            var str = '<select><option value="10">每页显示10条</option>';
            if (perPage == 50) {
                str += '<option value="50" selected="selected">每页显示50条</option>';
                str += '<option value="100">每页显示100条</option>';
                str += '<option value="300">每页显示300条</option><option value="500">每页显示500条</option><option value="1000">每页显示1000条</option></select>';
            } else if (perPage == 100) {
                str += '<option value="50">每页显示50条</option>';
                str += '<option value="100" selected="selected">每页显示100条</option>';
                str += '<option value="300">每页显示300条</option><option value="500">每页显示500条</option><option value="1000">每页显示1000条</option></select>';
            } else if (perPage == 300) {
                str += '<option value="50">每页显示50条</option>';
                str += '<option value="100">每页显示100条</option>';
                str += '<option value="300" selected="selected">每页显示300条</option><option value="500">每页显示500条</option><option value="1000">每页显示1000条</option></select>';
            } else if (perPage == 500) {
                str += '<option value="50">每页显示50条</option>';
                str += '<option value="100">每页显示100条</option>';
                str += '<option value="300">每页显示300条</option><option value="500" selected="selected">每页显示500条</option><option value="1000">每页显示1000条</option></select>';
            } else if (perPage == 1000) {
                str += '<option value="50">每页显示50条</option>';
                str += '<option value="100">每页显示100条</option>';
                str += '<option value="300">每页显示300条</option><option value="500">每页显示500条</option><option value="1000" selected="selected">每页显示1000条</option></select>';
            } else {
                str += '<option value="50">每页显示50条</option>';
                str += '<option value="100">每页显示100条</option>';
                str += '<option value="300">每页显示300条</option><option value="500">每页显示500条</option><option value="1000">每页显示1000条</option></select>';
            }
            return str;
        }
        ;

        function onRequest() {
            if (opts.ajax.on) {
                opts.ajax.ajaxStart();
                $.ajax({
                    url: opts.ajax.url,
                    type: opts.ajax.type,
                    data: getParam(),
                    contentType: "application/x-www-form-urlencoded;utf-8",
                    async: true,
                    cache: false,
                    timeout: 60000,
                    error: function () {
                        alert("访问服务器超时，请重试，谢谢！")
                    },
                    success: function (data) {
                        responseHandle(data);
                        createPageBar();

                    }
                })
            } else {
                createPageBar()
            }
        }
        ;

        function responseHandle(data) {
            var pageCountId = opts.ajax.pageCountId;
            var resultPageCount = 1;
            var allCountId = opts.ajax.allCountId;
            var resultAllCount = 0;
            switch ((opts.ajax.dataType)) {
                case "json":
                    try {
                        data = eval("(" + data + ")");
                    } catch (err) {
                    } finally {
                        resultPageCount = eval("data." + pageCountId);
                        resultAllCount = eval("data." + allCountId);
                    }
                    ;
                    break;
                case "xml":
                    resultPageCount = $(data).find(pageCountId).text();
                    resultAllCount = $(data).find(allCountId).text();
                    break;
                default:
                    if (document.all) {
                        resultPageCount = $(data).find("input:hidden[id='" + pageCountId + "']").val();
                        resultAllCount = $(data).find("input:hidden[id='" + allCountId + "']").val();
                    } else {
                        resultPageCount = $(data).filter("input:hidden[id='" + pageCountId + "']").val();
                        resultAllCount = $(data).filter("input:hidden[id='" + allCountId + "']").val();
                    }
                    break
            }
            ;
            opts.pageCount = resultPageCount;
            opts.allCount = resultAllCount;
            var rowsObj=$(data);
            if(opts.singleCheck){

            }

            if(opts.rowCheck){
                for (var i=0;i<rowsObj.length-2;i++){
                    var tr = rowsObj[i];
                    if(opts.contextMenu){
                        $(tr).contextMenu(opts.contextMenuParam);
                    }


                    $(tr).on('click',function () {
                        var chox=$(this).find('input[type=checkbox]:eq(0)');
                        var cid=$(this).find('input[type=checkbox]:eq(0)').attr('id');
                        if(opts.singleCheck){
                            $(this).siblings().find('input[type=checkbox]:eq(0)').prop('checked',false);
                            $(this).find('input[type=checkbox]:eq(0)').prop('checked',false);
                            $(this).siblings().removeClass('checked');
                            $(this).removeClass('checked');
                            opts.checkedId.length=0;
                        }
                        if(!chox.is(':checked')){
                            chox.prop('checked',true);
                            if(opts.saveChecked){
                            opts.checkedId.push(cid);
                            }
                        }else {
                            chox.prop('checked',false);
                            $(tr).removeClass('checked');
                            opts.checkedId.splice(opts.checkedId.indexOf(cid),1);
                           
                        }

                        //console.log(opts.checkedId);
                        $('.allcheckbox').data('checkIds',opts.checkedId);

                    });

                    if( opts.checkedId.length>0){
                        var tchox=$(tr).find('input[type=checkbox]:eq(0)');
                        var tcid=$(tr).find('input[type=checkbox]:eq(0)').attr('id');
                       if( opts.checkedId.indexOf(tcid)>=0){
                           $(tr).addClass('checked');
                           tchox.prop('checked',true);
                       }
                    }
                }
                if(opts.singleCheck){
                    $('.allcheckbox').off('click');
                    $('.allcheckbox').attr('disabled','disabled');
                }else {
                    $('.allcheckbox').off('click');
                    $('.allcheckbox').on('click', function () {
                        var table = $(this).parents('.treeTable');
                        var ckbs = $(table).find('tbody tr input[type=checkbox]');
                        $(ckbs).each(function (index, ck) {
                            var tr = $(ck).parents('tr');
                            var cid = $(ck).attr('id');
                            if ($(".allcheckbox").is(":checked")) {
                                ck.checked = true;
                                tr.addClass('checked');
                                opts.checkedId.push(cid);
                            } else {
                                ck.checked = false;
                                tr.removeClass('checked');
                                if (opts.checkedId.indexOf(cid) >= 0) {
                                    opts.checkedId.splice(opts.checkedId.indexOf(cid), 1);
                                }
                            }
                        });
                        $('.allcheckbox').data('checkIds', opts.checkedId);
                    });
                }
            }
            if(opts.rowNumber&&opts.allCount>0){

                    for (var i=0;i<rowsObj.length-2;i++) {
                        if (rowsObj.length - 2 <= opts.perPage) {

                            if (opts.currPage) {
                                if (opts.currPage <= 1) {
                                    td = $("<td>" + (i + 1) + "</td>");
                                } else {
                                    td = $("<td>" + ((opts.currPage-1) * opts.perPage+(i + 1)) + "</td>")
                                }
                            } else {
                                td = $("<td>" + (i + 1) + "</td>");
                            }
                        }
                        var tr = rowsObj[i];
                        var fc = tr.cells[0];
                        $(fc).after(td);
                        if(opts.showTitle){
                            $(tr.cells).each(function (index,cell) {
                                var title=$(cell).attr("title");
                                if(!title){
                                    //var cellHtml=$(cell).html();
                                    //cellHtml=clearHtmlFormat(cellHtml);
                                  //  $(cell).attr("title",$(cell).html());
                                    $(cell).attr('title',cell.innerText);
                                }
                            });
                        }
                    }
             }
            opts.ajax.callback(rowsObj)
        };

        function clearHtmlFormat(html) {
            if(html.indexOf("<")>=0){
              html=html.substring(html.indexOf("<"),html.indexOf(">")+1);
              html=clearHtmlFormat(html);
            }else {
                return html;
            }
        }

        function createPageBar() {
            var links = opts.panel.links;
            opts.currPage = opts.currPage > opts.pageCount ? opts.pageCount : opts.currPage;
            var currPage = opts.currPage;
            var pageCount = parseInt(opts.pageCount);
            var tempPage = parseInt(opts.pageNumber / 2);
            var pageNumber = opts.pageNumber;
            var perPage = opts.perPage;
            var str = getpageCount(perPage);
            if (opts.panel.first_on) {
                str += "<a href='" + links + "' title='1'>" + opts.panel.first + "</a>";
            }
            ;
            if (opts.panel.prev_on) {
                if (currPage == 1) {
                    str += "<span class=\"disabled\" title=\"" + opts.panel.prev + "\">" + opts.panel.prev + " </span>";
                } else {
                    str += "<a href='" + links + "' title='" + (currPage - 1) + "'>" + opts.panel.prev + " </a>";
                }
            }
            ;
            var firstPage = lastPage = 1;
            firstPage = currPage - tempPage > 0 ? firstPage = currPage - tempPage : 1;
            if (firstPage + pageNumber > pageCount) {
                lastPage = pageCount + 1;
                firstPage = lastPage - pageNumber
            } else {
                lastPage = firstPage + pageNumber
            }
            ;
            if (firstPage <= 0) {
                firstPage = 1
            }
            ;
            for (firstPage; firstPage < lastPage; firstPage++) {
                if (firstPage == currPage) {
                    str += "<span class=\"current\" title=\"" + firstPage + "\">" + firstPage + "</span>";
                } else {
                    str += "<a href='" + links + "' title='" + firstPage + "'>" + firstPage + "</a>";
                }
            }
            ;
            if (opts.panel.next_on) {
                if (currPage == pageCount) {
                    str += "<span class=\"disabled\" title=\"" + opts.panel.next + "\">" + opts.panel.next + " </span>";
                } else {
                    str += "<a href='" + links + "' title='" + (currPage + 1) + "'>" + opts.panel.next + " </a>";
                }
            }
            ;
            if (opts.panel.last_on) {
                str += "<a href='" + links + "' title='" + pageCount + "'>" + opts.panel.last + "</a>";
            }
            ;
            str += getPanelTipInfo();

            //数据总条数
            str += "<span class='allcount'>查询到：" + parseInt(opts.allCount) + " 条数据</span>";

            obj.html(str);
            obj.children(":text").keypress(function (event) {
                var keycode = event.which;
                if (keycode == 13) {
                    var page = $(this).val();
                    if (checkInputPage(page)) {
                        obj.children("a").unbind("click");
                        obj.children("a").each(function () {
                            $(this).click(function () {
                                return false
                            })
                        });
                        opts.currPage = page;
                        onRequest();
                    }
                }
            });
            obj.children("a").each(function (index, element) {
                $(this).click(function () {
                    var page = parseInt(this.title);
                    page = page > 0 ? page : 1;
                    obj.children("a").unbind("click");
                    obj.children("a").each(function () {
                        $(this).click(function () {
                            return false
                        })
                    });
                    opts.currPage = page;
                    opts.ajax.onClick(page);
                    onRequest();
                    $(this).focus();
                    return false
                });
            });
            obj.children("select").change(function () {

                obj.children("a").unbind("click");
                obj.children("a").each(function () {
                    $(this).click(function () {
                        return false;
                    })
                });

                opts.pageNumber=parseInt($(this).val());
                $(obj).data('pageNum',opts.pageNumber);
                opts.perPage = parseInt($(this).val());
                opts.currPage = 1;
                opts.ajax.onClick(opts.currPage);
                //opts.ajax.onClick(page);
                onRequest();
                $(this).focus();
                return false;
            });
        }
        ;
        var opts = $.extend(true, defaults, param);
        opts.id = obj.attr("id");
        obj.addClass(opts.cssStyle);
        onRequest();
        var method = {};
        method.id = opts.id;
        method.getPage = function () {
            return opts.currPage
        };
        method.onReload = function () {
            opts.checkedId=[];
            $('.allcheckbox').data('checkIds',opts.checkedId);
            onRequest()
        };
        method.onLoad = function (param) {
            if (param && param instanceof Object) {
                opts.currPage = 1;
                opts.ajax.param = param.param;
                onRequest()
            }
        };
        method.jumpPage = function (page) {
            page = page < 1 ? 1 : page;
            page = page > opts.pageCount ? opts.pageCount : page;
            opts.currPage = page;
            onRequest()
        };
        return method
    }
    ;
})(jQuery);